
from django.views import View
from alipay import AliPay
from django.conf import settings
import os
from django import http
from django.shortcuts import render

from meiduo_mall.utils.views import LoginRequiredJSONMixin
from orders.models import OrderInfo
from meiduo_mall.utils.response_code import RETCODE
# from payment.models import Payment


# Create your views here.
from payment.models import Payment


class PaymentStatusView(LoginRequiredJSONMixin, View):
    """保存支付订单的状态"""
    def get(self, request):
        # 获取到所有的查询字符串参数
        query_dict = request.GET

        # 将查询字符串参数的类型转成标准的字典类型
        data = query_dict.dict()

        # 从查询字符串参数中提取并移除sign，不能参与签名验证
        signature = data.pop('sign')

        # 创建SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem")).read(),
            alipay_public_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                       "keys/alipay_public_key.pem")).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 使用SDK对象， 调用验证通知接口函数，得到验证的结果修改（将美多id和支付宝id绑定保存订单id，修改订单状态）
        success = alipay.verify(data, signature)

        # 如果验证通过，需要将支付宝状态进行处理（）
        if success:
            # 美多商城维护的订单ID
            order_id = data.get('out_trade_no')
            # 支付宝维护的订单ID
            trade_id = data.get('trade_no')
            Payment.objects.create(
                # order = order
                order_id=order_id,
                trade_id=trade_id
            )
            # 修改订单状态由"待支付"修改为"待评价"
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])

            # 响应结果
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            return http.HttpResponseForbidden('非法请求')


class PaymentView(LoginRequiredJSONMixin, View):
    """订单支付功能"""

    def get(self,request, order_id):
        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单信息错误')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem")).read(),
            alipay_public_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem")).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})